package com.zero.manager.controller;

import com.zero.manager.common.Page;
import com.zero.manager.common.Result;
import com.zero.manager.entity.User;
import com.zero.manager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 功能：admin表对应的控制请求接收
 * 作者：zero
 * 日期：2024/9/2 12:47
 */

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 新增用户信息
     */
    @PostMapping("/add")
    public Result add(@RequestBody User user) {
        try {
            userService.insertUser(user);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                return Result.error("重复插入数据");
            }
            return Result.error("插入数据失败");
        }
        return Result.success();
    }

    /**
     * 修改用户信息
     *
     * @param user
     * @return Result
     */
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateUser(user);
        return Result.success();
    }

    /**
     * 删除用户信息
     *
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.deleteUser(id);
        return Result.success();
    }

    /**
     * 展示所有用户信息
     *
     * @return
     */
    @GetMapping("/list")
    public Result list() {
        List<User> list = userService.list();
        return Result.success(list);
    }

    /**
     * 批量删除用户信息
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        userService.deleteByIds(ids);
        return Result.success();
    }

    /**
     * 模糊查询用户信息
     *
     * @param name
     * @return
     */
    @GetMapping("/listByLike")
    public Result listLike(@RequestParam String name) {
        List<User> user = userService.listLike(name);
        return Result.success(user);
    }

    /**
     * 多条件模糊查询用户信息
     *
     * @param username
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/byPage")
    public Result byPage(@RequestParam String username, @RequestParam String name, @RequestParam Integer pageNum, @RequestParam Integer pageSize) {
//        Map<String, Object> res = new HashMap<>();
//        res.put("userList", userService.byPage(username, name,pageNum,pageSize));
//        res.put("total", userService.getTotal());
        Page<User> page = new Page<>(userService.getTotal(username, name), userService.byPage(username, name, pageNum, pageSize));
        return Result.success(page);
    }
}
